package com.codingvip.link;

/**
 * @Author Tony.Han
 * @Created at 2020/4/4 9:45 下午
 * Desc:
 */
public class RemoveNode {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        ListNode l6 = new ListNode(6);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        RemoveNode removeNode = new RemoveNode();
        removeNode.removeNthFromEnd(l1, 6);
        System.out.println(l1.toString());

    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode h, slow, fast;
        h = head;
        slow = head;
        fast = head;
        int total = 0;
        while (fast != null) {
            fast = fast.next;
            total++;
            if (fast!=null && fast.next != null) {
                fast = fast.next;
                total++;
                slow = slow.next;
            } else if (fast != null) {
                fast = fast.next;
                total++;

            }else{
                break;
            }


        }
        int needDel = total - n + 1;
        int half = total / 2 + total % 2;
        if (needDel <= 0) {
            return head;
        }
        if (needDel == 1) {
            head=head.next ;
            return head;
        }
        if (needDel > half) {
            reMoveOneNode(head,slow, needDel, half);
        } else {
            reMoveOneNode(head,h, needDel, 1);
        }

        return head;

    }

    private void reMoveOneNode(ListNode head,ListNode slow, int needDel, int half) {

        while (slow != null) {
            if (half + 1 == needDel) {
                ListNode removeNode = slow.next;
                if(removeNode!=null){
                    slow.next = removeNode.next;
                }
                break;
            }{
                slow = slow.next;
                half++;
            }
        }
    }
}
